﻿using System;
using System.IO.Pipes;
using System.ServiceModel;

namespace WP7AccelerometerService
{
    /// <summary>
    /// WCF service consumed by windows phone client in order to report accelerometer data
    /// </summary>
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
    class WP7AccelerometerService : IWP7AccelerometerService
    {
        /// <summary>
        /// Named pipe name used to communicate with the driver
        /// </summary>
        private const string pipeName = @"Accelerometer";
        
        /// <summary>
        /// Named pipe instance
        /// </summary>
        private NamedPipeClientStream _pipe;

        /// <summary>
        /// Initializes a new instance of the WP7AccelerometerService class.
        /// </summary>
        public WP7AccelerometerService()
        {
            // create named pipe to communicate with the driver
            _pipe = new NamedPipeClientStream(".", pipeName, PipeDirection.Out);
            _pipe.Connect();
        }

        /// <summary>
        /// Reports current accelerometer data
        /// </summary>
        /// <param name="x">X axis component of acceleration, in G units</param>
        /// <param name="y">Y axis component of acceleration, in G units</param>
        /// <param name="z">Z axis component of acceleration, in G units</param>
        public void ReportAccelerometerData(float x, float y, float z)
        {
#if DEBUG
            // print reported accelerometer data to screen or debug output to ease debugging
            Debug.WriteLine("({0},{1},{2})", x, y, z);
            //Console.WriteLine("({0},{1},{2})", x, y, z);
#endif

            // prepare data as byte[] for named pipe
            byte[] xBytes = BitConverter.GetBytes(x);
            byte[] yBytes = BitConverter.GetBytes(y);
            byte[] zBytes = BitConverter.GetBytes(z);

            byte[] buffer = 
                { 
                    xBytes[0], xBytes[1], xBytes[2], xBytes[3], 
                    yBytes[0], yBytes[1], yBytes[2], yBytes[3], 
                    zBytes[0], zBytes[1], zBytes[2], zBytes[3] 
                };

            // write data to named pipe
            _pipe.Write(buffer, 0, buffer.Length);
        }
    }
}
